import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/approve_anchor_request.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'login_page.dart';

class RealNameAuthenticationPage extends StatefulWidget {
  const RealNameAuthenticationPage({Key key}) : super(key: key);

  @override
  _RealNameAuthenticationPageState createState() =>
      _RealNameAuthenticationPageState();
}

class _RealNameAuthenticationPageState
    extends State<RealNameAuthenticationPage> {
  File card_positive;

  File card_obverse;

  File hand_card;

  TextEditingController nameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController idCardController = TextEditingController();

//  List<PickedFile> _images = [];
  Future getPositiveImage(bool isTakePhoto) async {
    Navigator.pop(context);
    var image;
    try {
      image = await ImagePicker.pickImage(
          source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);
      if (image == null) {
        return;
      } else {
        setState(() {
          // _image = image;
          card_positive = File(image.path);
        });
      }
    } catch (e) {
      print("模拟器不支持相机！");
    }
  }

  Future getObverseImage(bool isTakePhoto) async {
    Navigator.pop(context);
    var image;
    try {
      image = await ImagePicker.pickImage(
          source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);
      if (image == null) {
        return;
      } else {
        setState(() {
          // _image = image;
          card_obverse = image;
        });
      }
    } catch (e) {
      print("模拟器不支持相机！");
    }
  }

  Future getHandImage(bool isTakePhoto) async {
    Navigator.pop(context);
    var image;
    try {
      image = await ImagePicker.pickImage(
          source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);
      if (image == null) {
        return;
      } else {
        setState(() {
          // _image = image;
          hand_card = File(image.path);
        });
      }
    } catch (e) {
      print("模拟器不支持相机！");
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
        backgroundColor: Color(0xff140c3d),
        appBar: AppBar(
          backgroundColor: Color(0xff140c3d),
          centerTitle: true,
          leading: GestureDetector(
            child: Icon(
              Icons.arrow_back_ios,
              size: SizeUtil.px(32),
              color: Color(0xfff3f3f3),
            ),
            onTap: () {
              Navigator.pop(context);
            },
          ),
          title: Text(
            '实名认证',
            style:
                TextStyle(color: Color(0xfff3f3f3), fontSize: SizeUtil.px(32)),
          ),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                width: double.infinity,
                height: SizeUtil.px(75),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                      colors: [
                        Color(0xfffe4d4e),
                        Color(0xffff2d8f),
                      ]),
                ),
                child: Center(
                  child: Text(
                    '以下信息均为必填项，为保证您的利益，请如实填写',
                    style: TextStyle(
                        fontSize: SizeUtil.px(23), color: Color(0xfff3f3f3)),
                  ),
                ),
              ),
              Container(
                width: double.infinity,
                color: Color(0xff2b244d),
                child: Column(
                  children: [
                    Container(
                      width: double.infinity,
                      height: SizeUtil.px(90),
                      child: Row(
                        children: [
                          SizedBox(
                            width: SizeUtil.px(64),
                          ),
                          Text(
                            '手机号',
                            style: TextStyle(
                                fontSize: SizeUtil.px(28),
                                color: Color(0xfff3f3f3)),
                          ),
                          SizedBox(
                            width: SizeUtil.px(37),
                          ),
                          Expanded(
                            child: TextField(
                                controller: phoneController,
                                style: TextStyle(
                                    fontSize: SizeUtil.px(23),
                                    color: Color(0xffd5d5d5)),
                                //输入框的样式
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: '请输入你的手机号',
                                  hintStyle: TextStyle(
                                    fontSize: SizeUtil.px(23),
                                    color: Color(0xffa5a5a5),
                                  ),
                                )),
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: SizeUtil.px(0)),
                      child: Divider(
                        height: SizeUtil.px(1),
                        indent: SizeUtil.px(36),
                        endIndent: SizeUtil.px(36),
                        color: Color(0xff707070),
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      child: Row(
                        children: [
                          SizedBox(
                            width: SizeUtil.px(64),
                          ),
                          Text(
                            '真实姓名',
                            style: TextStyle(
                                fontSize: SizeUtil.px(28),
                                color: Color(0xfff3f3f3)),
                          ),
                          SizedBox(
                            width: SizeUtil.px(37),
                          ),
                          Expanded(
                            child: TextField(
                                controller: nameController,
                                style: TextStyle(
                                    fontSize: SizeUtil.px(23),
                                    color: Color(0xffd5d5d5)),
                                //输入框的样式
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: '请填写你的真实姓名',
                                  hintStyle: TextStyle(
                                    fontSize: SizeUtil.px(23),
                                    color: Color(0xffa5a5a5),
                                  ),
                                )),
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: SizeUtil.px(0)),
                      child: Divider(
                        height: SizeUtil.px(1),
                        indent: SizeUtil.px(36),
                        endIndent: SizeUtil.px(36),
                        color: Color(0xff707070),
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      height: SizeUtil.px(90),
                      child: Row(
                        children: [
                          SizedBox(
                            width: SizeUtil.px(64),
                          ),
                          Text(
                            '身份证号',
                            style: TextStyle(
                                fontSize: SizeUtil.px(28),
                                color: Color(0xfff3f3f3)),
                          ),
                          SizedBox(
                            width: SizeUtil.px(37),
                          ),
                          Expanded(
                            child: TextField(
                                controller: idCardController,
                                style: TextStyle(
                                    fontSize: SizeUtil.px(23),
                                    color: Color(0xffd5d5d5)),
                                //输入框的样式
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: '请输入你的身份证号',
                                  hintStyle: TextStyle(
                                    fontSize: SizeUtil.px(23),
                                    color: Color(0xffa5a5a5),
                                  ),
                                )),
                          ),
                        ],
                      ),
                    ),

                  ],
                ),
              ),
              SizedBox(
                height: SizeUtil.px(17),
              ),
              Container(
                width: double.infinity,
                height: SizeUtil.px(323),
                color: Color(0xff2b244d),
                child: Column(
                  children: [
                    Align(
                      alignment: Alignment.topLeft,
                      child: Padding(
                        padding: EdgeInsets.only(
                            top: SizeUtil.px(23), left: SizeUtil.px(36)),
                        child: Text(
                          '上传身份证照片',
                          style: TextStyle(
                              fontSize: SizeUtil.px(28),
                              color: Color(0xfff3f3f3)),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: SizeUtil.px(33),
                    ),
                    Row(
                      children: [
                        SizedBox(
                          width: SizeUtil.px(36),
                        ),
                        Container(
                          width: SizeUtil.px(332.53),
                          height: SizeUtil.px(210.13),
                          child: InkWell(
                            child: card_positive == null
                                ? Image.asset(
                                    'assets/images/id_card_forward.png')
                                : _generatePositiveImages(),
                            onTap: () {
                              _pickPositiveImage();
                            },
                          ),
                        ),
                        SizedBox(
                          width: SizeUtil.px(12),
                        ),
                        Container(
                          width: SizeUtil.px(332.53),
                          height: SizeUtil.px(210.13),
                          child: InkWell(
                            child: card_obverse == null
                                ? Image.asset('assets/images/id_card_back.png')
                                : _generateObverseImages(),
                            onTap: () {
                              _pickObverseImage();
                            },
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(
                height: SizeUtil.px(12),
              ),
              Container(
                width: double.infinity,
                height: SizeUtil.px(350),
                color: Color(0xff2b244d),
                child: Column(
                  children: [
                    Align(
                      alignment: Alignment.topLeft,
                      child: Padding(
                        padding: EdgeInsets.only(
                            top: SizeUtil.px(23), left: SizeUtil.px(36)),
                        child: Text(
                          '上传身份证照片',
                          style: TextStyle(
                              fontSize: SizeUtil.px(28),
                              color: Color(0xfff3f3f3)),
                        ),
                      ),
                    ),
                    Align(
                      alignment: Alignment.topLeft,
                      child: Padding(
                        padding: EdgeInsets.only(
                            top: SizeUtil.px(10), left: SizeUtil.px(36)),
                        child: Text(
                          '(请根据图示手持证件拍照，确保证件信息清晰可见)',
                          style: TextStyle(
                              fontSize: SizeUtil.px(23),
                              color: Color(0xffff215d)),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: SizeUtil.px(21),
                    ),
                    Row(
                      children: [
                        SizedBox(
                          width: SizeUtil.px(36),
                        ),
                        Container(
                          width: SizeUtil.px(332.53),
                          height: SizeUtil.px(210.13),
                          child: InkWell(
                            child:
                                Image.asset('assets/images/id_card_hand.png'),
                          ),
                        ),
                        SizedBox(
                          width: SizeUtil.px(12),
                        ),
                        Container(
                            width: SizeUtil.px(325),
                            height: SizeUtil.px(208),
                            child: DottedBorder(
                              borderType: BorderType.RRect,
                              color: Color(0xffa5a5a5),
                              radius: Radius.circular(SizeUtil.px(10)),
                              child: InkWell(
                                child: Center(
                                  child: hand_card == null
                                      ? Icon(
                                          Icons.add,
                                          size: SizeUtil.px(100),
                                          color: Color(0xffa5a5a5),
                                        )
                                      : _generateHandImages(),
                                ),
                                onTap: () {
                                  _pickHandImage();
                                },
                              ),
                            )),
                      ],
                    ),
                  ],
                ),
              ),
              Row(
                children: [
                  Container(
                    width: size.width / 2,
                    child: Center(
                      child: Text(
                        '手持证件照示例',
                        style: TextStyle(
                            fontSize: SizeUtil.px(28),
                            color: Color(0xffa5a5a5)),
                      ),
                    ),
                  ),
                  Container(
                    width: size.width / 2,
                    child: Center(
                      child: Text(
                        '手持证件正面照',
                        style: TextStyle(
                            fontSize: SizeUtil.px(28),
                            color: Color(0xffa5a5a5)),
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: SizeUtil.px(71),
              ),
              InkWell(
                child: Container(
                  width: SizeUtil.px(517),
                  height: SizeUtil.px(73),
                  decoration: BoxDecoration(
                      color: Color(0xffe62d6c),
                      borderRadius:
                          BorderRadius.all(Radius.circular(SizeUtil.px(43)))),
                  child: Center(
                    child: Text(
                      '立即认证',
                      style: TextStyle(
                          fontSize: SizeUtil.px(28), color: Color(0xfff3f3f3)),
                    ),
                  ),
                ),
                onTap: () {
                  approveAnchor();
                },
              ),
              SizedBox(
                height: SizeUtil.px(35),
              ),
              Center(
                child: RichText(
                  text: TextSpan(
                      text: '已阅读并同意',
                      style: TextStyle(
                          fontSize: SizeUtil.px(20), color: Color(0xffa5a5a5)),
                      children: [
                        TextSpan(
                          text: '《用户充值协议》',
                          style: TextStyle(
                              fontSize: SizeUtil.px(20),
                              color: Color(0xffff215d)),
                          recognizer: TapGestureRecognizer()..onTap = () {},
                        )
                      ]),
                ),
              )
            ],
          ),
        ));
  }

  ///底部弹框
  _pickHandImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 160,
              child: Column(
                children: <Widget>[
                  _takeHandPhotoItem('拍照', true),
                  _takeHandPhotoItem('从相册选择', false),
                ],
              ),
            ));
  }

  ///底部弹框
  _pickPositiveImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 160,
              child: Column(
                children: <Widget>[
                  _takePositivePhotoItem('拍照', true),
                  _takePositivePhotoItem('从相册选择', false),
                ],
              ),
            ));
  }

  ///底部弹框
  _pickObverseImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 160,
              child: Column(
                children: <Widget>[
                  _takeObversePhotoItem('拍照', true),
                  _takeObversePhotoItem('从相册选择', false),
                ],
              ),
            ));
  }

  _takeHandPhotoItem(String title, bool isTakePhoto) {
    print(isTakePhoto);
    return GestureDetector(
      child: ListTile(
        leading: Icon(
          isTakePhoto ? Icons.camera_alt : Icons.photo_library,
        ),
        title: Text(title),
        onTap: () => getHandImage(isTakePhoto),
      ),
    );
  }

  _takePositivePhotoItem(String title, bool isTakePhoto) {
    print(isTakePhoto);
    return GestureDetector(
      child: ListTile(
        leading: Icon(
          isTakePhoto ? Icons.camera_alt : Icons.photo_library,
        ),
        title: Text(title),
        onTap: () => getPositiveImage(isTakePhoto),
      ),
    );
  }

  _takeObversePhotoItem(String title, bool isTakePhoto) {
    print(isTakePhoto);
    return GestureDetector(
      child: ListTile(
        leading: Icon(
          isTakePhoto ? Icons.camera_alt : Icons.photo_library,
        ),
        title: Text(title),
        onTap: () => getObverseImage(isTakePhoto),
      ),
    );
  }

  /// 封装图片面板
  _generateHandImages() {
    return Stack(
      children: <Widget>[
        ClipRRect(
          //圆角效果
          borderRadius: BorderRadius.circular(SizeUtil.px(12)),
          child: Image.file(hand_card,
              width: SizeUtil.px(332.53),
              height: SizeUtil.px(210.13),
              fit: BoxFit.fill),
        ),
        Positioned(
          right: 5,
          top: 5,
          child: GestureDetector(
            onTap: () {
              setState(() {
                hand_card = null;
              });
            },
            child: ClipOval(
              //圆角删除按钮
              child: Container(
                padding: EdgeInsets.all(5),
                decoration: BoxDecoration(color: Colors.black54),
                child: Icon(
                  Icons.close,
                  size: 20,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 封装图片面板
  _generatePositiveImages() {
    return Stack(
      children: <Widget>[
        ClipRRect(
          //圆角效果
          borderRadius: BorderRadius.circular(SizeUtil.px(12)),
          child: Image.file(card_positive,
              width: SizeUtil.px(332.53),
              height: SizeUtil.px(210.13),
              fit: BoxFit.fill),
        ),
        Positioned(
          right: 5,
          top: 5,
          child: GestureDetector(
            onTap: () {
              setState(() {
                card_positive = null;
              });
            },
            child: ClipOval(
              //圆角删除按钮
              child: Container(
                padding: EdgeInsets.all(5),
                decoration: BoxDecoration(color: Colors.black54),
                child: Icon(
                  Icons.close,
                  size: 20,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 封装图片面板
  _generateObverseImages() {
    return Stack(
      children: <Widget>[
        ClipRRect(
          //圆角效果
          borderRadius: BorderRadius.circular(SizeUtil.px(12)),
          child: Image.file(card_obverse,
              width: SizeUtil.px(332.53),
              height: SizeUtil.px(210.13),
              fit: BoxFit.fill),
        ),
        Positioned(
          right: 5,
          top: 5,
          child: GestureDetector(
            onTap: () {
              setState(() {
                card_obverse = null;
              });
            },
            child: ClipOval(
              //圆角删除按钮
              child: Container(
                padding: EdgeInsets.all(5),
                decoration: BoxDecoration(color: Colors.black54),
                child: Icon(
                  Icons.close,
                  size: 20,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  approveAnchor() async {
    String name = nameController.text;
    String idCard = idCardController.text;
    String phone = phoneController.text;
    if (name == null ||
        idCard == null ||
        card_obverse == null ||
        card_positive == null ||
        hand_card == null || phone == null) {
      TxUtils.showToast('认证信息不能为空', context);
    } else {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String appToken = prefs.getString('app-token');
      FormData formData = FormData.fromMap({
        'name': name,
        'id_card': idCard,
        'phone': phone,
        'type' : 2 ,
        'card_positive': await MultipartFile.fromFile(card_positive.path),
        'card_obverse': await MultipartFile.fromFile(card_obverse.path),
        'hand_card': await MultipartFile.fromFile(hand_card.path),
      });
      var dio = new Dio();
      dio.options.headers = {"usertoken": appToken};
      var response ;
      try{
        response = await dio.post("http://119.28.131.94:82/app/user/anchor/approve", data: formData);
        var result = response.data;
        if (result['code'] == -1) {
          TxUtils.showErrorToast('登录失效，请重新登录', context);
          Navigator.pop(context);
          Navigator.of(context).push(MaterialPageRoute(
            builder: (context) {
              return LoginPage(
                arguments: {'loginCode': '-1'},
              );
            },
          ));
        } else if (result['code'] == 413) {
          TxUtils.showErrorToast('文件太大，无法上传', context);
        } else {
          TxUtils.showToast(result['data'], context);
          Navigator.of(context).pop("refresh");
        }
      }catch(e){
        print(e);
        if(e.response.statusCode == 413){
          TxUtils.showErrorToast('文件太大，无法上传', context);
        }
      }

    }
  }
}
